import http from 'wechat-http'
http.baseURL = 'https://live-api.itheima.net'
// 请求拦截器
http.intercept.request = (options) => {
  // 指定默认的头信息
  const defaultHeader = {}
  // 权限认证
  defaultHeader.Authorization = 'Bearer ' + getApp().token

  // 合并头信息
  options.header = Object.assign({}, defaultHeader, options.header)
  // 拦截器处理后的请求参数

  return options
}
http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    if (config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack.pop()
      const redirectURL = currentPage.route
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/' + redirectURL
      })

    }
    const { code, data: { token, refreshToken } } = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: 'Bearer ' + getApp().refreshToken
      }
    })
    if (code !== 10000) return wx.utils.toast()
    getApp().settoken('token', token)
    getApp().settoken('refreshToken', refreshToken)
    config = Object.assign(config, {
      header: {
        Authorization: 'Bearer ' + token
      }
    })
    return http(config)
  }
  return data
}
wx.http = http